#include"stdafx.h"
#include"SQLexpression.h"

vector <string>SqlEx::simpleParse(string str) {
	vector <string>result;
	int more = str.find(">");
	int less = str.find("<");
	int equal = str.find("=");
	if (more != -1) {
		result.push_back(str.substr(0, more));
		result.push_back(">");
		result.push_back(str.substr(more + 1, str.length() - more - 1));
	}
	else if (less != -1) {
		result.push_back(str.substr(0, less));
		result.push_back("<");
		result.push_back(str.substr(less + 1, str.length() - less - 1));
	}
	else if (equal != -1) {
		result.push_back(str.substr(0, equal));
		result.push_back("=");
		result.push_back(str.substr(equal + 1, str.length() - equal - 1));
	}
	return result;
}

void  SqlEx::where(string sql, vector<struct_where>&wh)
{
	string temp = "";
	int andPos = sql.find("and");
	int orPos = sql.find("or");
	while (andPos != -1 || orPos != -1) {
		if (andPos != -1 && orPos != -1) {
			if (andPos <= orPos) {
				temp = sql.substr(0, andPos);
				vector<string>vec = simpleParse(temp);
				struct_where temp_where;
				temp_where.key = vec[0];
				temp_where.operater = vec[1];
				temp_where.value = vec[2];
				temp_where.joiner = "&";
				wh.push_back(temp_where);
				sql = sql.substr(andPos + 3, sql.length() - andPos - 3);
			}
			else
			{
				temp = sql.substr(0, orPos);
				vector<string>vec = simpleParse(temp);
				struct_where temp_where;
				temp_where.key = vec[0];
				temp_where.operater = vec[1];
				temp_where.value = vec[2];
				temp_where.joiner = "|";
				wh.push_back(temp_where);
				sql = sql.substr(orPos + 2, sql.length() - orPos - 2);
			}
		}
		else if (andPos == -1) {
			temp = sql.substr(0, orPos);
			vector<string>vec = simpleParse(temp);
			struct_where temp_where;
			temp_where.key = vec[0];
			temp_where.operater = vec[1];
			temp_where.value = vec[2];
			temp_where.joiner = "|";
			wh.push_back(temp_where);
			sql = sql.substr(orPos + 2, sql.length() - orPos - 2);
		}
		else {
				temp = sql.substr(0, andPos);
				vector<string>vec = simpleParse(temp);
				struct_where temp_where;
				temp_where.key = vec[0];
				temp_where.operater = vec[1];
				temp_where.value = vec[2];
				temp_where.joiner = "&";
				wh.push_back(temp_where);
				sql = sql.substr(andPos + 3, sql.length() - andPos - 3);
		}
		temp = "";
		andPos = sql.find("and");
		orPos = sql.find("or");
	}

	vector<string>vec = simpleParse(sql);
	struct_where temp_where;
	temp_where.key = vec[0];
	temp_where.operater = vec[1];
	temp_where.value = vec[2];
	wh.push_back(temp_where);
}